package com.example.arithmeticleetcode.leetcode.dec;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-12-09 11:27
 **/
public class PlaceNQueens02 {

    public static void main(String[] args) {
        new PlaceNQueens02().placeNQueens(4);
    }

    int[] queens;

    /**
     * 标记着某一列是否有皇后
     */
    boolean[] cols;

    /**
     * 标记左对角线是否有皇后 k < 0 左上角->右下角
     */
    boolean[] leftTop;

    /**
     * 标记右对角线是否有皇后 右上角->左下角
     */
    boolean[] rightTop;

    /**
     * 多少种摆法
     */
    int ways;

    void placeNQueens(int n) {
        if (n < 1) return;
        queens = new int[n];
        cols = new boolean[n];
        leftTop = new boolean[(n << 1) - 1];
        rightTop = new boolean[leftTop.length];
        place(0);
        System.out.println(n + "皇后，一共有" + ways + "种摆法！");
    }

    /**
     * 从第几行开始摆放皇后
     *
     * @param row
     */
    void place(int row) {

        if (row == cols.length) {
            show();
            ways++;
            return;
        }

        for (int col = 0; col < cols.length; col++) {

            //剪枝操作

            //在当前列上
            if (cols[col]) continue;
            //在当前对角线上
            int ltIndex = row - col + cols.length - 1;
            if (leftTop[ltIndex]) continue;
            int rtIndex = row + col;
            if (rightTop[rtIndex]) continue;


            //在第row第col列摆放皇后
            queens[row] = col;
            cols[col] = true;
            leftTop[ltIndex] = true;
            rightTop[rtIndex] = true;
            place(row + 1);

            cols[col] = false;
            leftTop[ltIndex] = false;
            rightTop[rtIndex] = false;

        }
    }


    void show() {
        for (int row = 0; row < cols.length; row++) {
            for (int col = 0; col < cols.length; col++) {
                if (queens[row] == col) {
                    System.out.print("1 ");
                } else {
                    System.out.print("0 ");
                }
            }
            System.out.println();
        }
        System.out.println("----------------------------------------");
    }
}
